//
//  UIButton+QSExtension.m
//  ZengLongSeSha
//
//  Created by apple on 2017/6/23.
//  Copyright © 2017年 Song. All rights reserved.
//

#import "UIButton+QSExtension.h"
#import <objc/runtime.h>

static NSString *btnSelectorBlockKey = @"btnSelectorBlockKey";

@implementation UIButton (QSExtension)
- (void)addActionWithSelectorBlock:(btnSelectorBlock)btnSelectorBlock
{
    objc_setAssociatedObject(self, &btnSelectorBlockKey, btnSelectorBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    [self addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
}

/**
 *  按钮点击事件
 */
- (void)clickBtn:(UIButton *)btn
{
    btnSelectorBlock block = objc_getAssociatedObject(self, &btnSelectorBlockKey);
    
    if (block) {
        block(btn);
    }
}

/**
 *  @brief  使用颜色设置按钮背景
 */
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state
{
    [self setBackgroundImage:[UIButton imageWithColor:backgroundColor] forState:state];
}

/**
 *  根据颜色制作一张图片
 */
+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}
@end
